package com.deekian.weixin.confirm;

import com.deekian.weixin.confirm.mould.WeixinAppInfo;
import com.deekian.weixin.confirm.util.SimpleOkHttpUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.OkHttpClient;

public class WeixinClient {
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private WeixinAppInfo info;
    OkHttpClient client = new OkHttpClient();

    public WeixinClient(WeixinAppInfo info) {
        this.info = info;
    }

    public WeixinClient(String appId, String secretKey) {
        this.info = new WeixinAppInfo(appId, secretKey);
    }

    public AccessTokenResponse accessToken(AccessTokenRequest request) {
        SimpleOkHttpUtils.Result result = SimpleOkHttpUtils.doGet(ACCESS_TOKEN_URL, request.toParam(this.info));
        if (result.normal) {
            if (result.status == 200) {
                JsonObject res = new JsonParser().parse(result.result).getAsJsonObject();
                if (res.has("errcode")) {
                    throw new WeixinResponseException(res.get("errcode").getAsInt(), res.get("errmsg").getAsString());
                } else {
                    return new AccessTokenResponse(
                            res.get("access_token").getAsString(),
                            res.get("expires_in").getAsLong(),
                            res.get("refresh_token").getAsString(),
                            res.get("openid").getAsString(),
                            res.get("scope").getAsString()
                    );
                }
            }
        }
        throw new RuntimeException(result.toString());
    }
}
